<%@page import="java.sql.Date"%>
<%@page import="classes.HomeworkManagerStudent"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="org.apache.commons.io.FilenameUtils"%>
<%@page import="org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.tomcat.util.http.fileupload.FileItem"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.tomcat.util.http.fileupload.FileUploadException"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>


<%
try {
	String group = "";
	String id ="";
	String url = "C:/Users/Davidlek/workspace/Project/HomeWorkManager/WebContent/lecturerHomework/";
	boolean empty = false;
    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            String fieldname = item.getFieldName();
            String fieldvalue = item.getString();
            
            if(fieldname.equals("id")){
  				id = fieldvalue;
            }
            if(fieldname.equals("group")){
            	group = fieldvalue;
            }
            
            
        } else {
            // Process form file field (input type="file").
            String fieldname = item.getFieldName();
            String filename = FilenameUtils.getName(item.getName());
            
            	InputStream filecontent = item.getInputStream();
            	url += filename;
           		FileOutputStream fos = new FileOutputStream(url);//TODO: url
            	int i;
            	while((i = filecontent.available()) > 0){
            		byte[] b = new byte[i];
            		filecontent.read(b,0,b.length);                
            		fos.write(b);  
            	}
            	filecontent.close();  
            	fos.flush();  
            	fos.close(); 
            	
		}
    }
    
   HomeworkManagerStudent.updateSomething(Integer.parseInt(id), "fileName_student",url);
   HomeworkManagerStudent.updateSomething(Integer.parseInt(id), "upload_time",new Date(System.currentTimeMillis()).toString());
   RequestDispatcher dispatch = request
			.getRequestDispatcher("subject.jsp?group=" + group);
	dispatch.forward(request, response);
    
} catch (FileUploadException e) {
    throw new ServletException("Cannot parse multipart request.", e);
}





%>

</body>
</html>